﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.


using System;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.MultiTenancy;
using System.Transactions;
using GCT.Foundation.Seed.Host;
using Abp.EntityFrameworkCore.Uow;
using GCT.Foundation.Seed.Tenants;
using Microsoft.EntityFrameworkCore;
using GCT.Foundation.EntityFrameworkCore;

namespace GCT.Foundation.Seed
{
    public class FoundationTemplateSeedHelper
    {
        public static void SeedHostDb(IIocResolver iocResolver)
        {
            WithDbContext<FoundationTemplateDbContext>(iocResolver, SeedHostDb);
        }

        public static void SeedHostDb(FoundationTemplateDbContext context)
        {
            context.SuppressAutoSetTenantId = true;

            // 初始化宿主的种子数据
            new InitialHostDbBuilder(context).Create();

            // 初始化 Default 租户的种子数据
            new DefaultTenantBuilder(context).Create();
            new TenantRoleAndUserBuilder(context, 1).Create();
            new DefaultSettingsBuilder(context, 1).Create();
            //new BaseDynamicMenuDataBuilder(context).Create();
        }

        private static void WithDbContext<TDbContext>(IIocResolver iocResolver, Action<TDbContext> contextAction)
            where TDbContext : DbContext
        {
            using (var uowManager = iocResolver.ResolveAsDisposable<IUnitOfWorkManager>())
            {
                using (var uow = uowManager.Object.Begin(TransactionScopeOption.Suppress))
                {
                    var context = uowManager.Object.Current.GetDbContext<TDbContext>(MultiTenancySides.Host);

                    contextAction(context);

                    uow.Complete();
                }
            }
        }
    }
}
